import React, { useState, useEffect } from 'react';
import { TextField, List, ListItem, ListItemIcon, ListItemText, Box } from '@mui/material';
import ActionDialog from './ActionDialog';
import Checkbox from '../../general/Checkbox';
import { NETPYNE_COMMANDS } from '../../../constants';
import { evalPythonMessage } from '../../general/GeppettoJupyterUtils';

const saveOptions = [
  {
    label: 'High-level Network Parameters (netParams)',
    label2: 'Cell rules, connectivity rules, etc',
    state: 'netParams',
  },
  {
    label: 'Simulation Configuration (simConfig)',
    label2: 'duration, recorded variables, etc',
    state: 'simConfig',
  },
  {
    label: 'Instantiated Network',
    label2: 'All cells, connections, etc',
    state: 'netCells',
  },
  {
    label: 'Simulation Data',
    label2: 'Spikes, traces, etc',
    state: 'simData',
  },
];

const getTimeStamp = (): string => {
  return new Date().toUTCString().replace(',', '').replace(/[ ,:]/g, '_');
};

interface SaveFileDialogProps {
  open?: boolean;
  onRequestClose?: () => void;
  [key: string]: any;
}

/**
 * SaveFileDialog Component
 * Dialog for saving model as JSON file with options for what to save
 */
const SaveFileDialog: React.FC<SaveFileDialogProps> = ({
  open = false,
  onRequestClose,
  ...otherProps
}) => {
  const [fileName, setFileName] = useState(`output_${getTimeStamp()}`);
  const [netParams, setNetParams] = useState(true);
  const [simConfig, setSimConfig] = useState(true);
  const [simData, setSimData] = useState(true);
  const [netCells, setNetCells] = useState(true);
  const [disableNetCells, setDisableNetCells] = useState(false);
  const [disableSimData, setDisableSimData] = useState(false);

  useEffect(() => {
    // Check if instance or simulation data exists
    evalPythonMessage('netpyne_geppetto.doIhaveInstOrSimData', [])
      .then((response: any) => {
        setDisableNetCells(!response.haveInstance);
        setDisableSimData(!response.haveSimData);
        setNetCells(response.haveInstance);
        setSimData(response.haveSimData);
      })
      .catch((error) => {
        console.error('Error checking instance/simulation data:', error);
      });
  }, []);

  const toggleSaveOption = (state: string): void => {
    switch (state) {
      case 'netParams':
        setNetParams((prev) => !prev);
        break;
      case 'simConfig':
        setSimConfig((prev) => !prev);
        break;
      case 'simData':
        setSimData((prev) => !prev);
        break;
      case 'netCells':
        setNetCells((prev) => !prev);
        break;
    }
  };

  const isChecked = (state: string): boolean => {
    switch (state) {
      case 'netParams':
        return netParams;
      case 'simConfig':
        return simConfig;
      case 'simData':
        return simData;
      case 'netCells':
        return netCells;
      default:
        return false;
    }
  };

  const isDisabled = (index: number): boolean => {
    // Index 2 = netCells, Index 3 = simData
    if (index === 2) {
      return disableNetCells;
    }
    if (index === 3) {
      return disableNetCells; // Based on original code logic
    }
    return false;
  };

  return (
    <ActionDialog
      command={NETPYNE_COMMANDS.exportModel}
      message="EXPORTING_MODEL"
      buttonLabel="Save"
      title="Save as JSON file"
      args={{
        fileName,
        netParams,
        simConfig,
        simData,
        netCells,
      }}
      open={open}
      onRequestClose={onRequestClose}
      {...otherProps}
    >
      <TextField
        variant="filled"
        fullWidth
        value={fileName}
        label="File name"
        onChange={(e) => setFileName(e.target.value)}
        sx={{
          '& .MuiFilledInput-root': {
            '&::before': {
              display: 'none',
            },
          },
        }}
      />
      <Box sx={{ mt: 2 }}>
        <List
          sx={{
            display: 'flex',
            flexWrap: 'wrap',
          }}
        >
          {saveOptions.map((saveOption, index) => (
            <ListItem key={index} sx={{ width: '50%' }}>
              <ListItemIcon>
                <Checkbox
                  disabled={isDisabled(index)}
                  onChange={() => toggleSaveOption(saveOption.state)}
                  checked={isChecked(saveOption.state)}
                  noBackground
                />
              </ListItemIcon>
              <ListItemText
                primary={saveOption.label}
                secondary={saveOption.label2}
              />
            </ListItem>
          ))}
        </List>
      </Box>
    </ActionDialog>
  );
};

export default SaveFileDialog;

